<template>
  <div class="page-container">
    <el-card class="reservation-form">
      <template #header>
        <div class="form-header">
          <h2>📅 新建场地预约</h2>
          <el-button type="primary" @click="submitReservation" size="small">
            <i class="el-icon-upload"></i> 提交预约
          </el-button>
        </div>
      </template>
      
      <el-form :model="reservationForm" :rules="rules" ref="reservationFormRef" label-width="120px" >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="场馆名称" prop="venueName">
              <el-select 
                v-model="reservationForm.venueName" 
                placeholder="请选择场馆"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="venue in venueList"
                  :key="venue.id"
                  :label="venue.venueName"
                  :value="venue.venueName"
                  :disabled="venue.status !== '空闲'"
                >
                  <span style="float: left">{{ venue.venueName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ venue.status }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="预约日期" prop="bookingDate">
              <el-date-picker
                v-model="reservationForm.bookingDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="reservation-history">
      <template #header>
        <h2>📋 我的预约记录</h2>
      </template>
      
      <el-table 
        :data="reservationHistory" 
        stripe
        border
        style="width: 100%"
        :default-sort="{prop: 'bookingDate', order: 'descending'}"
        align="center"
      >
        <!-- 原有列定义保持不变，增加列宽和样式 -->
        <el-table-column 
          prop="venueName" 
          label="场地名称" 
          sortable
          width="220"
        ></el-table-column>
        
        <el-table-column 
          prop="bookingDate"
          label="预约时间" 
          sortable
          width="150"
        ></el-table-column>
        
        <el-table-column 
          prop="status" 
          label="预约状态" 
          sortable
          width="120"
        >
          <template #default="scope">
            <el-tag
              :type="getTagType(scope.row.status)"
              size="medium"
              effect="light"
              round
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column 
          label="操作" 
          width="150"
        >
          <template #default="scope">
            <el-button 
              type="primary" 
              icon="Edit" 
              circle
              @click="editReservation(scope.row)"
            />
            <el-button 
              type="danger" 
              icon="Delete" 
              circle
              @click="deleteReservation(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>

  <el-dialog v-model="editDialogVisible" title="修改预约" width="30%">
    <el-form :model="editForm" :rules="rules" ref="editFormRef">
      <el-form-item label="场馆名称" prop="venueName">
        <el-select v-model="editForm.venueName" placeholder="请选择场馆">
          <el-option
            v-for="venue in venueList"
            :key="venue.id"
            :label="venue.venueName"
            :value="venue.venueName"
            :disabled="venue.status !== '空闲'"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预约日期" prop="bookingDate">
        <el-date-picker
          v-model="editForm.bookingDate"
          type="date"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmEdit">确认修改</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.page-container {
  padding: 24px;
  background: #f5f7fa;
}

.reservation-form {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.reservation-history {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.el-table {
  margin-top: 16px;
}

.el-tag {
  font-weight: 500;
  letter-spacing: 0.5px;
}
</style>

<script setup>
import {onMounted, ref} from 'vue'
import request from '@/utils/request'
import {ElMessage, ElMessageBox} from 'element-plus'

// 获取用户名
const currentUser = sessionStorage.getItem('userId')
console.log('当前用户ID:', currentUser)
// 预约表单数据
const reservationForm = ref({
  venueName: '',
  bookingDate: '',
  brokerId: 0
})

// 场馆列表
const venueList = ref([])
// 过往预约记录
const reservationHistory = ref([])

// 表单验证规则
const rules = {
  venueName: [
    { required: true, message: '请选择预约场馆名称', trigger: 'change' }
  ],
  bookingDate: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ]
}

const reservationFormRef = ref(null)

// 获取场馆列表
const getVenueList = async () => {
  try {
    const response = await request.get('/getVenueInfo')
    venueList.value = response.data.data
    // console.log('获取场馆列表成功', response.data.data)
    // console.log('场馆列表:', venueList.value)
  } catch (error) {
    console.error('获取场馆列表失败', error)
  }
}

// 获取过往预约记录
const getReservationHistory = async () => {
  try {
    const response = await request.get(`/getReservationHistory/${currentUser}`)
    reservationHistory.value = response.data.data
  } catch (error) {
    console.error('获取过往预约记录失败', error)
  }
}

// 提交预约
const submitReservation = async () => {
  if (!reservationFormRef.value) return
  try {
    await reservationFormRef.value.validate()
    reservationForm.value.brokerId = currentUser
    const response = await request.post('/submitReservation', {
      ...reservationForm.value,
      bookingDate: reservationForm.value.bookingDate // 确保使用最新值
    })
    
    // 清空旧数据缓存
    if (response.data.code === 200) {
      ElMessage.success('预约提交成功')
      reservationHistory.value = [] // 清空缓存
      await getReservationHistory()
      reservationFormRef.value.resetFields()
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    // 优先显示后端错误信息
    if (error?.response?.data) {
      ElMessage.error(error.response.data.msg)
    } else {
      ElMessage.error('提交失败：内容不能为空')
    }
  }
}

const editDialogVisible = ref(false)
const editForm = ref({ venueName: '', bookingDate: '' })
const editFormRef = ref(null)
const currentEditId = ref(null)
// 修改预约（新增方法）
// 修改后的editReservation方法
const editReservation = (row) => {
  editForm.value = { 
    venueName: row.venueName,
    bookingDate: row.bookingDate
  }
  currentEditId.value = row.id
  editDialogVisible.value = true
}

const confirmEdit = async () => {
  try {
    await editFormRef.value.validate()
    const response = await request.put(`/updateReservation/${currentEditId.value}`, {
      venueName: editForm.value.venueName,
      bookingDate: editForm.value.bookingDate,
      brokerId: currentUser
    })
    
    if (response.data.code === 200) {
      ElMessage.success('修改成功')
      reservationHistory.value = [] // 清空缓存
      await getReservationHistory()
      editDialogVisible.value = false
    } else {
      // 显示后端返回的具体错误
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    // 显示完整错误信息
    if (error?.response?.data) {
      ElMessage.error(error.response.data.msg)
    } else {
      ElMessage.error('修改失败：' + error.message)
    }
  }
}

// 删除预约
const deleteReservation = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除${row.venueName}的预约记录吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const response = await request.delete(`/deleteReservation/${row.id}`)
    if (response.data.code === 200) {
      ElMessage.success('删除预约成功')
      await getReservationHistory() // 添加 await 确保刷新
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    ElMessage.error('删除失败：' + (error.response?.data?.msg || '服务器错误'))
  }
}

// 根据状态获取 tag 类型
const getTagType = (status) => {
  if (status === '审核中') return 'warning'
  if (status === '已接受') return 'success'
  if (status === '已拒绝') return 'danger'
  return ''
}

onMounted(() => {
  getVenueList()
  getReservationHistory()
})
</script>
